import React, { useState } from 'react';
import type { FormProps } from 'antd';
import { Form, Input, Table, Space, Card, Row, Col } from 'antd';
import AsyncButton from '@renderer/components/AsyncButton';
import { CodeOutlined } from '@ant-design/icons';

type FieldType = {
  devUrl?: string;
};

interface WindowInfo {
  id: string;
  url: string;
  title: string;
  createdAt: Date;
}

const Dev: React.FC = () => {
  const [windows, setWindows] = useState<WindowInfo[]>([]);
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);

  // Preset URLs configuration
  const presetUrls = [
    { name: 'yss', url: 'http://101.201.210.111:49000' },
  ];

  const createWindow = async (url: string, title: string = '新窗口') => {
    setIsLoading(true);
    try {
      const result = await window.windowApi.create({
        width: 800,
        height: 600,
        url,
        title
      });

      console.log(result);


      setWindows(prev => [
        ...prev,
        {
          id: result.windowId,
          url,
          title,
          createdAt: new Date()
        }
      ]);

    } catch (error) {
      console.error("Failed to create window:", error);

    } finally {
      setIsLoading(false);
    }
  };

  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    await createWindow(values.devUrl || '');
    form.resetFields();
  };

  const handleCloseWindow = async (id: string) => {
    try {
      await window.windowApi.close(id);
      setWindows(prev => prev.filter(window => window.id !== id));
    } catch (error) {
      console.error("Failed to close window:", error);
    }
  };

  const handleReloadWindow = async (id: string) => {
    try {
      await window.windowApi.reload(id);
    } catch (error) {
      console.error("Failed to reload window:", error);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: (id: string) => <span className="window-id">{id.substring(0, 8)}...</span>,
    },
    {
      title: '网址',
      dataIndex: 'url',
      key: 'url',
      render: (url: string) => url ? <a href={url} target="_blank" rel="noopener noreferrer">{url}</a> : '-',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: Date) => date.toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: WindowInfo) => (
        <Space size="middle">
          <AsyncButton size="small" onClick={() => handleReloadWindow(record.id)}>
            刷新
          </AsyncButton>
          <AsyncButton size="small" danger onClick={() => handleCloseWindow(record.id)}>
            关闭
          </AsyncButton>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Card title="快速访问" style={{ marginBottom: 20 }}>
        <Row gutter={[16, 16]}>
          {presetUrls.map((item, index) => (
            <Col key={index} span={8}>
              <AsyncButton
                type="primary"
                onClick={() => createWindow(item.url)}
                loading={isLoading}
              >
                {item.name}
              </AsyncButton>
            </Col>
          ))}
        </Row>
      </Card>

      <Card title="自定义窗口">
        <Form
          form={form}
          name="开发者"
          layout="vertical"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="开发地址"
            name="devUrl"
            rules={[{ required: true, message: '请输入开发地址!' }]}
          >
            <Input placeholder="例如: http://localhost:3000" />
          </Form.Item>

          <Form.Item>
            <AsyncButton type="primary" htmlType="submit" loading={isLoading}>
              创建新窗口
            </AsyncButton>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`窗口管理 (${windows.length} 个)`} style={{ marginTop: 20 }}>
        <Table
          columns={columns}
          dataSource={windows}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
          bordered
          scroll={{ x: true }}
        />
      </Card>
    </div>
  );
};

export default Dev;
